package limitreader

import "io"

type limitReader struct {
	r        io.Reader
	limit    int64
	readByte int64
}

func (l *limitReader) Read(p []byte) (n int, err error) {
	if l.readByte < l.limit {
		ReadByte := int64(len(p))
		if l.readByte+ReadByte > l.limit {
			ReadByte = l.limit - l.readByte
		}
		n, err = l.r.Read(p[:ReadByte])
		l.readByte += int64(n)
		if l.readByte >= l.limit && err == nil {
			err = io.EOF
		}
		return n, err
	}
	return 0, io.EOF
}

func LimitReader(r io.Reader, n int64) io.Reader {
	return &limitReader{
		r:        r,
		limit:    n,
		readByte: 0,
	}
}
